package com.example.repository;

import com.example.model.Appointment;
import com.example.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
    
    // 根据客户查找预约
    Page<Appointment> findByCustomer(User customer, Pageable pageable);
    
    // 根据状态查找预约
    Page<Appointment> findByStatus(Appointment.AppointmentStatus status, Pageable pageable);
    
    // 根据预约类型查找
    List<Appointment> findByType(Appointment.AppointmentType type);
    
    // 根据时间范围查找预约
    @Query("SELECT a FROM Appointment a WHERE a.appointmentTime BETWEEN :startTime AND :endTime")
    List<Appointment> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
    
    // 查找今日预约
    @Query("SELECT a FROM Appointment a WHERE a.appointmentTime >= :startOfDay AND a.appointmentTime < :endOfDay")
    List<Appointment> findTodayAppointments(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);
    
    // 查找待确认的预约
    List<Appointment> findByStatusOrderByCreatedAtDesc(Appointment.AppointmentStatus status);
    
    // 统计各状态预约数量
    @Query("SELECT a.status, COUNT(a) FROM Appointment a GROUP BY a.status")
    List<Object[]> countByStatus();
    
    // 查找即将到期的预约（1小时内）
    @Query("SELECT a FROM Appointment a WHERE a.appointmentTime BETWEEN :now AND :oneHourLater AND a.status = 'CONFIRMED'")
    List<Appointment> findUpcomingAppointments(LocalDateTime now, LocalDateTime oneHourLater);
}
